from flask import Flask
import configparser
import os

def create_app():
    """应用工厂函数"""
    # 获取应用根目录的绝对路径
    basedir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
    
    # 显式设置模板和静态文件夹路径
    app = Flask(__name__, 
                template_folder=os.path.join(basedir, 'templates'),
                static_folder=os.path.join(basedir, 'static'))
    
    # 加载配置
    config = configparser.ConfigParser()
    config.read(os.path.join(basedir, 'config.ini'), encoding='utf-8')
    
    # 应用配置
    app.secret_key = config['app']['SECRET_KEY']
    # 确保上传目录使用绝对路径
    app.config['UPLOAD_FOLDER'] = os.path.join(basedir, config['upload']['UPLOAD_FOLDER'])
    app.config['MAX_CONTENT_LENGTH'] = int(config['upload']['MAX_CONTENT_LENGTH'])
    
    # 确保上传目录存在
    if not os.path.exists(app.config['UPLOAD_FOLDER']):
        os.makedirs(app.config['UPLOAD_FOLDER'])
    
    # 注册蓝图
    from app.routes import main, auth, products, transactions, store, system, search
    
    app.register_blueprint(main.bp)
    app.register_blueprint(auth.bp)
    app.register_blueprint(products.bp)
    app.register_blueprint(transactions.bp)
    app.register_blueprint(store.bp)
    app.register_blueprint(system.bp)
    app.register_blueprint(search.bp)
    
    return app

